<template>
    <div>
        <div class="chat" v-if="this.user.Identify!='3'">
            <div id="chat_expand">
                <span @click="UpAndDown">
                    <span v-if="expand"><ArrowDownBold /></span>
                    <span v-else><ArrowUpBold /></span>
                </span>
                <span id="chat_expandMove">客服</span>
                <span v-if="!expand">
                    <el-badge :value="messageNum" :max="10" class="item"></el-badge>
                </span>
            </div>
            <div>
                <div v-show="expand" class="chat_context">
                    <el-scrollbar height="206px"    
                        v-loading="loading"
                        :element-loading-text="LoadingText">
                        <ul id="chatContextList">
                            <li
                                v-for="(item,index) in MessageData" 
                                :class="item!=undefined && item.sender==MyId?'':'float_right'" 
                                :data-sender="item!=undefined &&item.sender"
                                :data-status="item!=undefined &&item.status"
                                :key="index">
                                <div v-if="item!=undefined">{{ item.senderName }}</div>
                                <div v-if="item!=undefined">{{ item.context }}</div>
                            </li>
                        </ul>
                    </el-scrollbar>
                </div>
                <div v-show="expand" class="chat_operator">
                    <div class="chat_operatorList">
                        <div class="chat_operatorAppoint">
                            <p>
                                在线:<span id="count">{{ count }}</span>人 <button class="msg_close" @click="delLog(this.MyId,this.user.Identify)">清空</button>
                            </p>
                            <el-select v-model="chat_operatorSelect" class="m-2" placeholder="发送给" size="small">
                                <el-option
                                    v-for="(item,index) in options"
                                    :key="index"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </div>
                    </div>
                    <div class="chat_operatorInp">
                        <el-input
                            @keyup.enter="sendMessage"
                            v-model="sendContent"
                            :rows="2"
                            type="textarea"
                            placeholder="请输入您想说的话..."
                        />
                        <div class="chatSubmit">
                            <button id="ReInit" v-if="loading" @click="onReInit">重新连接</button>
                            <button id="submit" v-else @click="onSubmit">提交</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div id="mainwindow" v-else>
			<div class="mainLeft">
				<div class="Me">
                    <el-icon class="serviceIcon"><Service /></el-icon>
                    客服--{{this.user.userName}}
				</div>
				<div class="User">
					<ul class="UserList">
						<li id="HigeShow" v-for="(item,index) in MessagesKeys" :key="index" @click="SwitchUser(item)"><img src="../../../../assets/person.png" />{{ item }} <button class="msg_close" @click="delLog(item,this.user.Identify)">清空</button></li>
					</ul>
				</div>
			</div>
			<div class="mainRight">
				<div class="contentTitle">用户标识 -- {{ MessageTitle }}</div>
				<div class="content">
                    <ul id="chatContextList">
                        <li
                            v-for="(item,index) in MessagesList" 
                            :class="item.sender==MyId?'':'float_right'" 
                            :data-sender="item.sender"
                            :data-status="item.status"
                            :key="index">
                            <div>{{ item.senderName }}</div>
                            <div>{{ item.context }}</div>
                        </li>
                    </ul>
				</div>
				<div class="Operate">
					<div class="Operateboard"></div>
					<div class="OperateSubmit">
                        <el-input
                            @keyup.enter="sendMessage"
                            v-model="sendContent"
                            :rows="5"
                            type="textarea"
                            placeholder="请输入您想说的话..."
                        />
                        <div class="chatSubmit" style="right: 9px;bottom: 10px;">
                            <button id="ReInit" style="height: 27px;width: 76px;" v-if="loading" @click="onReInit">重新连接</button>
                            <button id="submit" style="height: 27px;width: 76px;" v-else @click="onSubmit">提交</button>
                        </div>
					</div>
				</div>
			</div>
		</div>
    </div>
</template>
<script>
import { defineComponent } from '@vue/composition-api'
import { useStore } from 'vuex' 
import { ElMessage  } from 'element-plus'
import { getCurrentInstance} from 'vue'
export default defineComponent({
    data(){
        return{
            MessageData:[],
            data:{
                id: '',
                sid: '',
                name:'',
                context: null
            },                      //要发送的信息
            chat_operatorSelect:'', //选择某个人
            options:[],                  //总消息数
            Messages:new Map(),
            MessagesList:[],
            MessagesKeys:[],
            MessageTitle:'',
            sendContent:'',     //要发送的内容
            count:'',           //总人数
            MyId:'',            //自己的id
            user:null,          //用户信息
            socket:null,        //socket对象
            loading:true,
            LoadingText:"努力连接中...",
            expand:true,
            messageNum:0        //框折叠时显示的信息数量
        }
    },
    setup() {
        // vuex的数据对象
        const store = useStore();

        const { proxy } = getCurrentInstance();

        return{
            store,
            proxy
        }
    },
    created(){
        this.user = this.store.state.UserMessage;
        this.MyId = this.user.Id;
        if(this.user==null) return;
        this.initSocket();
    },
    mounted () {
        var chat_expand = document.getElementById("chat_expandMove");
        var clientx = 0,clienty = 0,flag = false;
        if(!chat_expand) return;
        chat_expand.onmousedown = function(e){
            flag = true;
            this.style.cursor = "all-scroll";
            clientx = e.offsetX;
            clienty = e.offsetY;
        }
        document.onmousemove = function(e){
            if(!flag) return;
            chat_expand.parentNode.parentNode.style.cssText = `top:${e.clientY - clienty }px;left:${e.clientX - clientx - 43}px`;
        }
        document.onmouseup = function(e){
            flag = false;
            chat_expand.style.cursor = "default";
        }
    },
    methods:{
        initSocket(){
            if(this.user==undefined) return;
            this.socket = new WebSocket(`${this.SocketUrl}/websocket/${this.user.Id}/${this.user.Identify}`);
            this.store.dispatch("asyncStoreSocket",this.socket);
            this.socket.onopen = this.getOpen;
            this.socket.onmessage = this.getMessage;
            this.socket.onerror = this.getError;
            this.socket.onclose = this.destroySocket;
        },
        getOpen(){
            console.log("尝试连接");
            this.loading = false;
        },
        getMessage(e){
            this.loading = false;
            this.messageNum+=1;
            let c = JSON.parse(e.data);
            if(c.flag==0&&this.user.Identify == "3"){
                this.createMap(c.data);
            }else if(c.flag==0&&this.user.Identify != "3"){
                this.createlist(c);
            }else{
                this.create(c);
            }
        },
        getError(e){
            console.log("连接失败");
            this.loading = true;
            this.LoadingText = "连接失败";
        },
        destroySocket(){
            this.loading = true;
            this.LoadingText = "断开连接";
        },
        onReInit(){
            this.initSocket();
        },
        onSubmit(){
            if(this.chat_operatorSelect == ''){
                ElMessage({
                    message: '选择发送的目标',
                    type: 'warning',
                })
                return;
            }
            this.data.id = this.chat_operatorSelect + '';
            this.data.sid = this.user.Id +'';
            this.data.name = this.user.name?this.user.name:this.user.userName;
            this.data.context = this.sendContent;
            this.data.identify = this.user.Identify+'';
            if(this.data.context=="") return;
            this.sendContent = '';
            this.socket.send(JSON.stringify(this.data));
        },
        UpAndDown(){
            let chat = document.getElementsByClassName("chat")[0];
            this.expand = !this.expand;
            this.messageNum = 0;
            if(this.expand){
                chat.id = "chatShow";
            }else{
                chat.id = "chatHide";
            }
        },
        sendMessage(e){
            this.onSubmit();
        },
        delLog(msg,identify){
            let self = this;
            let url = identify==3?"deleteService":"deleteUser";
            self.$http.get(`${self.baseUrl}/chat/${url}?id=${msg+''}`).then(res=>{
                ElMessage({
                    message:"删除成功",
                    type:'success'
                })
                self.Messages.delete(msg+"")
                let o = self.Messages.get(self.chat_operatorSelect);
                self.MessagesList = o!=undefined?o:[];
            })
        },
        SwitchUser(msg){
            this.MessageTitle = msg;
            this.chat_operatorSelect = msg+"";
            this.MessagesList = this.Messages.get(msg+"");
        },
        create(msg){
            this.count = msg.user.length;
            this.createPerson(msg);
            if(this.user.Identify == "3"){
                this.addMessages(msg);
            }else{
                this.createMessage(msg);
            }
        },
        createMap(msg){
            this.Messages.clear();
            for(let key in msg){
                this.Messages.set(key,msg[key]);
            }
            this.MessagesKeys = [...this.Messages.keys()];
            this.MessagesList = this.Messages.get(this.MessagesKeys[0]+'');
            this.chat_operatorSelect = this.MessagesKeys[0];
        },
        createlist(msg){
            this.MessageData = msg.data;
            this.count = msg.user.length;
            this.createPerson(msg);
        },
        addMessages(msg){
            if(!msg.hasOwnProperty("data")) return;
            let l = null;
            if(msg.data.sender==this.MyId){
                l = this.Messages.get(msg.data.recipient+"");
            }else{
                l = this.Messages.get(msg.data.sender+"");
            }
            if(l==null||l==void 0){
                this.Messages.set(msg.data.sender+"",msg.data);
                this.MessagesKeys = [...this.Messages.keys()];
            }else{
                let d = msg.data;
                let data = l;
                l = [];
                data = Array.isArray(data) ? data : [];
                data.push(d);
                l = data;
                // this.MessagesList.push(d);
            }
        },
        createPerson(msg){
            if(msg.user==undefined||msg.user=='') return;
            this.options = this.dealUser(msg);
            let data = this.options;
            this.options = [];
            if(this.user.Identify=="3") data.push({name:"All",id:"All"})
            this.options = data;
            this.chat_operatorSelect = this.options.length==0?"":this.options[0].id;
        },
        dealUser(msg){
            let use = msg.user;
            let result = [];
            for(let i=0;i<use.length;i++){
                let row = {};
                row["name"] = use[i];
                row["id"] = use[i];
                result.push(row)
            }  
            return result;
        },
        createMessage(msg){
            let d = msg.data;
            let data = this.MessageData;
            this.MessageData = [];
            data = Array.isArray(data) ? data : [];
            data.push(d)
            this.MessageData = data;
        }
    }
})
</script>
<style scoped>
 * {
    margin: 0;
    padding: 0;
}

.chat {
    width: 350px;
    height: fit-content;
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 200;
}
#chatShow{
    height: fit-content;
}
#chatHide{
    height: 26px;
}
#chat_expand{
    width: 100%;
    border-radius: 3px;
    height: 26px;
    background-color: rgb(102 168 255 / 79%);
    margin: auto;
    color: #fff;
}
#chat_expand span:nth-child(1){
    width: 20px;
    height: 20px;
    cursor: pointer;
    float: left;
    margin: 1px 10px 0 13px;
}
#chat_expand span:nth-child(2){
    width: 246px;
    margin-left: 18px;
    float: left;
    line-height: 26px;
    font-size: 18px;
}
#chat_expand span:nth-child(3){
    float: right;
    margin-right: 10px;
    line-height: 31px;
}
.chat_context {
    width: 96%;
    background-color: rgb(255, 255, 255);
    height: 206px;
    margin: 0 auto 3px auto;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-top: 1px solid #ccc;
}
.chat_context p{
    width: 100%;
    text-align: center;
}
#chatContextList{
    padding: 10px;
    width: calc(100% - 20px);
}
#chatContextList li{
    list-style-type: none;
    width: 100%;
    overflow: hidden;
    margin: 5px 0;
}
#chatContextList li div:nth-child(1){
    font-size: 10px;
    float: left;
    margin: 0 5px;
    padding-top: 3px;
}
#chatContextList li div:nth-child(2){
    font-size: 14px;
    padding: 5px 11px;
    background-color: #a2f89a;
    max-width: 67%;
    overflow: hidden;
    float: left;
    border-radius: 3px;
}
.serviceIcon{
    font-size: 26px;
    float: left;
    margin: 12px 0 0 20px;
}
.chat_operator {
    width: 96%;
    margin: auto;
    height: 19%;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    position: relative;
    background-color: #ffffff;
}

.chat_operatorList {
    width: 100%;
    height: 26px;
    border-radius: 8px;
    border-bottom: 1px dashed #ccc;
    border-top: 1px dashed #ccc;
}

.chat_operatorInp {
    width: 100%;
    overflow: hidden;
}
.chat_operatorAppoint{
    overflow: hidden;
    display: flex;
    justify-content: space-evenly;
}
.chat_operatorAppoint p{
    font-size: 10px;
    color: #424044;
    margin: 0 10px 0 20px;
    width: 108px;
    line-height: 24px;
}
.chat_operatorAppoint p span{
    color: #14c1f191;
    margin: 0 5px 0 5px;
}

.chatSubmit {
    position: absolute;
    right: 4px;
    bottom: 3px;
}

.chatSubmit button {
    width: 60px;
    height: 25px;
    background-color: #55a1e3;
    border: none;
    border-radius: 5px;
    color: #fff;
    cursor: pointer;
}
.float_right div{
    float: right !important;
}

#mainwindow{
    width: 95%;
    position: absolute;
    height: 93%;
    top: 20px;
    left: 30px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 1px 1px 6px 4px #ccc;
}
.mainLeft{
    width: 26%;
    float: left;
    height: 100%;
}
.Me{
    width: 100%;
    height: 50px;
    background-color: #ecf3f7;
    border-right: 1px solid #ccc;
    line-height: 50px;
    text-indent: 1em;
    color: #151515;
    font-weight: 400;
}
.Me img{
    width: 38px;
    height: 36px;
    margin: 8px -2px 0 14px;
    float: left;
}
.User{
    width: 100%;
    background-color: #f2f8fc;
    height: calc(100% - 50px);
}
.UserList{
    list-style-type: none;
    width: 100%;
    height: calc(100% - 36px);
    overflow: auto;
}
.UserList li{
    width: 100%;
    height: 50px;
    background-color: #eff2f3;
    line-height: 50px;
    color: #767272;
    border-bottom: 1px solid #ccc;
    border-top: 1px solid #ccc;
    cursor: pointer;
    text-indent: 19px;
    margin: 1px 0px;
    font-size: 17px;
}
.UserList li img{
    width: 33px;
    float: left;
    height: 31px;
    margin: 9px -13px 0px 9px;
}
.mainRight{
    float: right;
    width: 74%;
    height: 100%;
}
.contentTitle{
    width: 100%;
    height: 50px;
    background-color: #ecf3f7;
    line-height: 50px;
    text-indent: 2em;
    border-left: 1px solid #ccc;
    color: #161616;
    font-weight: bold;
}
.content{
    width: 100%;
    height: calc(100% - 230px);
    background-color: #ffffff;
    overflow: auto;
}
.Operate{
    width: 100%;
    height: 180px;
}
.Operateboard{
    width: 100%;
    height: 40px;
    background: #e4e4e4;
}
.OperateSubmit{
    width: 100%;
    height: calc(100% - 40px);
    background: lavenderblush;
}
#HigeShow{
    color: #000;
    background-color: #ccc;
}
.msg_close{
    width: 50px;
    background-color: #34bffb;
    border: none;
    border-radius: 10px;
    color: #fff;
    font-size: 13px;
    cursor: pointer;
    margin-left: 6px;
}
</style>